<div class="container">

<Breadcrumb :items="['menu.list', 'menu.list.searchTable']" />
<a-card class="general-card" :title="$t('menu.list.searchTable')">
  <a-row>
    <a-col :flex="1">

      <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
        <a-row :gutter="16">

          <a-col :span="8">
            <a-form-item field="trueName" label="姓名">
              <a-input v-model="formModel.trueName" placeholder="请输入姓名" />
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item field="mobile" label="手机号">
              <a-input v-model="formModel.mobile" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>


          <a-col :span="8">
            <a-form-item field="sex" label="性别">
              <a-select v-model="formModel.sex" :options="sexOptions" placeholder="请选择" />
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item field="email" label="邮箱">
              <a-input v-model="formModel.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>

          <!-- 状态搜索字段 -->
          <a-col :span="8">
            <a-form-item field="status" label="状态">
              <a-select v-model="formModel.status" :options="statusOptions" placeholder="请选择" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-col>

    <!-- 垂直分隔线 -->
    <a-divider style="height: 84px" direction="vertical" />

    <!-- 搜索和重置按钮区域 -->
    <a-col :flex="'86px'" style="text-align: right">
      <a-space direction="vertical" :size="18">
        <!-- 搜索按钮 -->
        <a-button type="primary" @click="search">
          <template #icon>
            <icon-search />
          </template>
          {{ $t('searchTable.form.search') }}
        </a-button>

        <!-- 重置按钮 -->
        <a-button @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          {{ $t('searchTable.form.reset') }}
        </a-button>
      </a-space>
    </a-col>
  </a-row>
  <!-- 分隔线 -->
  <a-divider style="margin-top: 0" />

  <!-- 表格操作区域 -->
  <a-row style="margin-bottom: 16px">
    <!-- 左侧操作按钮区域 -->
    <a-col :span="12">
      <a-space>
        <!-- 新增按钮 -->
        <a-button type="primary">
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('searchTable.operation.create') }}
        </a-button>

        <!-- 导入按钮 -->
        <a-upload action="/">
          <template #upload-button>
            <a-button>
              {{ $t('searchTable.operation.import') }}
            </a-button>
          </template>
        </a-upload>
      </a-space>
    </a-col>

    <!-- 右侧工具栏区域 -->
    <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
      <!-- 下载按钮 -->
      <a-button>
        <template #icon>
          <icon-download />
        </template>
        {{ $t('searchTable.operation.download') }}
      </a-button>

      <!-- 刷新按钮 -->
      <a-tooltip :content="$t('searchTable.actions.refresh')">
        <div class="action-icon" @click="search"><icon-refresh size="18" /></div>
      </a-tooltip>

      <!-- 表格密度设置下拉菜单 -->
      <a-dropdown @select="handleSelectDensity">
        <a-tooltip :content="$t('searchTable.actions.density')">
          <div class="action-icon"><icon-line-height size="18" /></div>
        </a-tooltip>
        <template #content>
          <!-- 密度选项列表 -->
          <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
          >
            <span>{{ item.name }}</span>
          </a-doption>
        </template>
      </a-dropdown>

      <!-- 列设置弹出框 -->
      <a-tooltip :content="$t('searchTable.actions.columnSetting')">
        <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
          <div class="action-icon"><icon-settings size="18" /></div>
          <template #content>
            <!--
              表格列设置区域
              新手须知：这里实现了表格列的显示/隐藏和拖拽排序功能
              使用Sortable.js库实现拖拽排序，在popupVisibleChange事件中初始化
            -->
            <div id="tableSetting">
              <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                <!-- 拖拽图标 -->
                <div style="margin-right: 4px; cursor: move">
                  <icon-drag-arrow />
                </div>
                <!-- 列显示/隐藏复选框 -->
                <div>
                  <a-checkbox
                      v-model="item.checked"
                      @change="handleChange($event, item as TableColumnData, index)"
                  ></a-checkbox>
                </div>
                <!-- 列标题 -->
                <div class="title">
                  {{ item.title === '#' ? '序列号' : item.title }}
                </div>
              </div>
            </div>
          </template>
        </a-popover>
      </a-tooltip>
    </a-col>
  </a-row>


  <a-table
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="cloneColumns as TableColumnData[]"
      :data="renderData"
      :bordered="false"
      :size="size"
      @page-change="onPageChange"
  >
    <!-- 自定义序号列插槽 -->
    <template #index="{ rowIndex }">
      <!-- 计算当前页中的序号 = 行索引 + 1 + (当前页码 - 1) * 每页条数 -->
      {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
    </template>

    <!-- 自定义性别列插槽 -->
    <template #sex="{ record }">
      {{ record.sex ? '男' : '女' }}
    </template>

    <!-- 自定义状态列插槽 -->
    <template #status="{ record }">
      <!-- 状态指示点，根据状态显示不同颜色 -->
      <span v-if="!record.status" class="circle"></span>
      <span v-else class="circle pass"></span>
      {{ record.status ? '启用' : '禁用' }}
    </template>

    <!-- 自定义操作列插槽 -->
    <template #operations="{ record }">
      <a-space>
        <!-- 查看按钮 -->
        <a-button type="text" size="small" @click="handleView(record)">
          <template #icon><icon-eye /></template>
          查看
        </a-button>

        <!-- 编辑按钮 -->
        <a-button type="text" size="small" @click="handleEdit(record)">
          <template #icon><icon-edit /></template>
          编辑
        </a-button>

        <a-button
            type="text"
            size="small"
            :status="record.status ? 'danger' : 'success'"
            @click="handleToggleStatus(record)"
        >
          <template #icon>
            <icon-poweroff v-if="record.status" />
            <icon-play-arrow-fill v-else />
          </template>
          {{ record.status ? '禁用' : '启用' }}
        </a-button>

        <!-- 删除按钮 -->
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
          <template #icon><icon-delete /></template>
          删除
        </a-button>
      </a-space>
    </template>
  </a-table>
</a-card>

<a-modal
    v-model:visible="detailVisible"
    :title="'会员详情'"
    :footer="false"
    @cancel="detailVisible = false"
    :mask-closable="true"
    modal-class="member-detail-modal"
    :width="700"
>
  <!-- 只有当有会员数据时才显示内容 -->
  <div class="member-detail-container" v-if="currentDetailMember">
    <!-- 顶部信息区域：包含头像、基本信息和操作按钮 -->
    <div class="member-detail-header">
      <!-- 头像区域 -->
      <div class="avatar-container">

        <a-avatar :size="80" :style="{ backgroundColor: currentDetailMember.status ? '#00b42a' : '#f53f3f' }">
          {{ currentDetailMember.trueName ? currentDetailMember.trueName.substring(0, 1) : 'U' }}
        </a-avatar>
        <!-- 状态标签 -->
        <div class="status-badge" :class="{ 'active': currentDetailMember.status }">
          {{ currentDetailMember.status ? '已启用' : '已禁用' }}
        </div>
      </div>

      <!-- 基本信息区域 -->
      <div class="basic-info">
        <!-- 会员姓名 -->
        <h2>{{ currentDetailMember.trueName || '未设置姓名' }}</h2>
        <!-- 用户ID信息 -->
        <div class="info-item">
          <icon-user /> 用户ID: {{ currentDetailMember.userId }}
        </div>
        <!-- 手机号信息 -->
        <div class="info-item">
          <icon-mobile /> {{ currentDetailMember.mobile }}
        </div>
        <!-- 邮箱信息 -->
        <div class="info-item">
          <icon-email /> {{ currentDetailMember.email || '未设置邮箱' }}
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <!-- 编辑按钮 -->
        <a-button type="outline" status="success" @click="handleEdit(currentDetailMember)">
          <template #icon><icon-edit /></template>
          编辑
        </a-button>

        <!-- 启用/禁用按钮 -->
        <a-button
            type="outline"
            :status="currentDetailMember.status ? 'danger' : 'success'"
            @click="handleToggleStatus(currentDetailMember)"
            style="margin-left: 8px;"
        >
          <template #icon>
            <icon-poweroff v-if="currentDetailMember.status" />
            <icon-play-arrow-fill v-else />
          </template>
          {{ currentDetailMember.status ? '禁用' : '启用' }}
        </a-button>
      </div>
    </div>

    <!-- 分隔线 -->
    <a-divider />


    <a-tabs default-active-key="1">
      <!-- 基本信息选项卡 -->
      <a-tab-pane key="1" title="基本信息">
        <div class="detail-section">
          <!-- 性别和生日信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">性别</div>
              <div class="detail-value">{{ currentDetailMember.sex ? '男' : '女' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">生日</div>
              <div class="detail-value">{{ currentDetailMember.birthday || '未设置' }}</div>
            </div>
          </div>

          <!-- 固定电话和QQ信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">固定电话</div>
              <div class="detail-value">{{ currentDetailMember.telephone || '未设置' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">QQ</div>
              <div class="detail-value">{{ currentDetailMember.qq || '未设置' }}</div>
            </div>
          </div>

          <!-- 地区和邮编信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">地区</div>
              <div class="detail-value">{{ currentDetailMember.area || '未设置' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">邮编</div>
              <div class="detail-value">{{ currentDetailMember.zip || '未设置' }}</div>
            </div>
          </div>

          <!-- 联系地址信息行（占满整行宽度） -->
          <div class="detail-row">
            <div class="detail-item full-width">
              <div class="detail-label">联系地址</div>
              <div class="detail-value">{{ currentDetailMember.contactAddr || '未设置' }}</div>
            </div>
          </div>
        </div>
      </a-tab-pane>

      <!-- 账户信息选项卡 -->
      <a-tab-pane key="2" title="账户信息">
        <div class="detail-section">
          <!-- 会员组和积分信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">会员组</div>
              <div class="detail-value">{{ currentDetailMember.groupId || '默认组' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">积分</div>
              <div class="detail-value">{{ currentDetailMember.point || 0 }}</div>
            </div>
          </div>

          <!-- 经验值和账户余额信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">经验值</div>
              <div class="detail-value">{{ currentDetailMember.exp || 0 }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">账户余额</div>
              <!-- 格式化余额显示，添加货币符号 -->
              <div class="detail-value">{{ currentDetailMember.balance ? `¥${currentDetailMember.balance}` : '¥0.00' }}</div>
            </div>
          </div>

          <!-- 注册时间和最后登录信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">注册时间</div>
              <div class="detail-value">{{ currentDetailMember.time || '未知' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">最后登录</div>
              <div class="detail-value">{{ currentDetailMember.lastLogin || '未登录' }}</div>
            </div>
          </div>

          <!-- 微信绑定信息行 -->
          <div class="detail-row">
            <div class="detail-item">
              <div class="detail-label">微信绑定</div>
              <div class="detail-value">
                <!-- 使用标签显示绑定状态 -->
                <a-tag color="green" v-if="currentDetailMember.openId">已绑定</a-tag>
                <a-tag color="gray" v-else>未绑定</a-tag>
              </div>
            </div>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</a-modal>

<!-- 会员编辑对话框 -->
<a-modal
    v-model:visible="editVisible"
    :title="editForm.userId ? '编辑会员' : '新增会员'"
    @ok="handleEditSubmit"
    @cancel="editVisible = false"
>
  <a-form :model="editForm" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
    <a-form-item field="trueName" label="姓名">
      <a-input v-model="editForm.trueName" placeholder="请输入姓名" />
    </a-form-item>
    <a-form-item field="mobile" label="手机号">
      <a-input v-model="editForm.mobile" placeholder="请输入手机号" />
    </a-form-item>
    <a-form-item field="email" label="邮箱">
      <a-input v-model="editForm.email" placeholder="请输入邮箱" />
    </a-form-item>
    <a-form-item field="sex" label="性别">
      <a-radio-group v-model="editForm.sex">
        <a-radio :value="true">男</a-radio>
        <a-radio :value="false">女</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item field="status" label="状态">
      <a-radio-group v-model="editForm.status">
        <a-radio :value="true">启用</a-radio>
        <a-radio :value="false">禁用</a-radio>
      </a-radio-group>
    </a-form-item>
  </a-form>
</a-modal>

<!-- 删除确认对话框 -->
<a-modal
    v-model:visible="deleteVisible"
    title="确认删除"
    @ok="handleDeleteConfirm"
    @cancel="deleteVisible = false"
    :ok-text="'确认删除'"
    :cancel-text="'取消'"
    :ok-button-props="{ status: 'danger' }"
    modal-class="delete-confirm-modal"
>
  <div class="delete-confirm-content">
    <div class="delete-icon">
      <icon-exclamation-circle-fill />
    </div>
    <div class="delete-info">
      <h3>您确定要删除该会员吗？</h3>
      <p>删除后数据将无法恢复，请谨慎操作。</p>
      <p v-if="currentMember" class="member-info">
        <span>用户ID: {{ currentMember.userId }}</span>
        <span>姓名: {{ currentMember.trueName }}</span>
      </p>
    </div>
  </div>
</a-modal>

<!-- 启用/禁用确认对话框 -->
<a-modal
    v-model:visible="toggleStatusVisible"
    :title="statusAction ? '确认禁用' : '确认启用'"
    @ok="handleToggleStatusConfirm"
    @cancel="toggleStatusVisible = false"
    :ok-text="statusAction ? '确认禁用' : '确认启用'"
    :cancel-text="'取消'"
    :ok-button-props="{ status: statusAction ? 'danger' : 'success' }"
    modal-class="status-confirm-modal"
>
  <div class="status-confirm-content">
    <div class="status-icon" :class="{ 'disable': statusAction }">
      <icon-poweroff v-if="statusAction" />
      <icon-play-arrow-fill v-else />
    </div>
    <div class="status-info">
      <h3>您确定要{{ statusAction ? '禁用' : '启用' }}该会员吗？</h3>
      <p>{{ statusAction ? '禁用后该会员将无法登录系统。' : '启用后该会员将恢复正常使用。' }}</p>
      <p v-if="currentMember" class="member-info">
        <span>用户ID: {{ currentMember.userId }}</span>
        <span>姓名: {{ currentMember.trueName || '未设置' }}</span>
        <span>当前状态: {{ currentMember.status ? '启用' : '禁用' }}</span>
      </p>
    </div>
  </div>
</a-modal>
</div>
</template>

<script lang="ts" setup>


// Vue核心功能导入
import { computed, ref, reactive, watch, nextTick } from 'vue'
// 国际化支持
import { useI18n } from 'vue-i18n'
// 加载状态钩子
import useLoading from '@/hooks/loading'

// API相关导入
import {
  queryMemberPage,  // 分页查询会员列表
  getMemberDetail,  // 获取会员详情
  updateMember,     // 更新会员信息
  toggleMemberStatus, // 切换会员状态(启用/禁用)
  deleteMember,     // 删除会员
  MemberRecord,     // 会员记录类型
  PageQuery,        // 分页查询参数类型
  MemberDetail      // 会员详情类型
} from '@/api/member'

// 类型定义导入
import { Pagination } from '@/types/global'  // 分页类型
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface'  // 下拉选项类型
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'   // 表格列类型
import type { DescData } from '@arco-design/web-vue/es/descriptions/interface'   // 描述列表类型

// 工具库导入
import cloneDeep from 'lodash/cloneDeep'  // 深拷贝工具
import Sortable from 'sortablejs'         // 拖拽排序库

// ArcoDesign图标组件导入
import {
  IconEdit,          // 编辑图标
  IconDelete,        // 删除图标
  IconPoweroff,      // 禁用图标
  IconPlayArrowFill, // 启用图标
  IconEye,           // 查看图标
  IconExclamationCircleFill, // 警告图标
  IconUser,          // 用户图标
  IconMobile,        // 手机图标
  IconEmail          // 邮箱图标
} from '@arco-design/web-vue/es/icon'

// ArcoDesign组件导入
import { Message, Modal } from '@arco-design/web-vue'  // 消息提示和模态框

// 定义表格密度类型
type SizeProps = 'mini' | 'small' | 'medium' | 'large'

// 扩展表格列类型，添加checked属性用于列显示控制
type Column = TableColumnData & { checked?: true }

const generateFormModel = () => {
  return {
    trueName: '',  // 姓名
    mobile: '',    // 手机号
    sex: '',       // 性别
    status: '',    // 状态
    email: '',     // 邮箱
  }
}

// 使用加载状态钩子
const { loading, setLoading } = useLoading(true)
// 使用国际化钩子
const { t } = useI18n()

// 表格数据
const renderData = ref<MemberRecord[]>([])
// 搜索表单数据
const formModel = ref(generateFormModel())
// 表格列配置(克隆，用于修改)
const cloneColumns = ref<Column[]>([])
// 显示列配置
const showColumns = ref<Column[]>([])

// 对话框可见性控制
const detailVisible = ref(false)        // 详情对话框
const editVisible = ref(false)          // 编辑对话框
const deleteVisible = ref(false)        // 删除确认对话框
const toggleStatusVisible = ref(false)  // 状态切换确认对话框

// 当前操作的会员数据
const currentMember = ref<MemberRecord | null>(null)
// 当前查看的会员详情
const currentDetailMember = ref<MemberDetail | null>(null)
// 状态操作类型：true表示禁用操作，false表示启用操作
const statusAction = ref(false)
// 编辑表单数据
const editForm = ref<MemberDetail>({
  userId: 0,       // 用户ID
  trueName: '',     // 姓名
  mobile: '',       // 手机号
  sex: true,        // 性别，默认为男
  status: true,     // 状态，默认为启用
  email: ''         // 邮箱
})

// 会员详情数据(描述列表格式)
const detailData = ref<DescData[]>([])

// 表格密度
const size = ref<SizeProps>('medium')

// 基础分页配置
const basePagination: Pagination = {
  current: 1,    // 当前页码
  pageSize: 3,   // 每页条数
}

// 分页数据(响应式)
const pagination = reactive({
  ...basePagination,
})

// 表格密度选项
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),  // 迷你
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),  // 小
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'), // 中
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),  // 大
    value: 'large',
  },
])

// 表格列配置
const columns = computed<TableColumnData[]>(() => [
  {
    title: t('searchTable.columns.index'), // 序号
    dataIndex: 'index',
    slotName: 'index',
  },
  {
    title: '用户ID',  // 用户ID列
    dataIndex: 'userId',
  },
  {
    title: '姓名',    // 姓名列
    dataIndex: 'trueName',
  },
  {
    title: '手机号',  // 手机号列
    dataIndex: 'mobile',
  },
  {
    title: '性别',    // 性别列
    dataIndex: 'sex',
    slotName: 'sex',  // 使用插槽自定义显示
  },
  {
    title: '邮箱',    // 邮箱列
    dataIndex: 'email',
  },
  {
    title: '状态',    // 状态列
    dataIndex: 'status',
    slotName: 'status', // 使用插槽自定义显示
  },
  {
    title: t('searchTable.columns.operations'), // 操作列
    dataIndex: 'operations',
    slotName: 'operations', // 使用插槽自定义操作按钮
  },
])

// 性别下拉选项
const sexOptions = computed<SelectOptionData[]>(() => [
  {
    label: '男',
    value: true,
  },
  {
    label: '女',
    value: false,
  },
])

// 状态下拉选项
const statusOptions = computed<SelectOptionData[]>(() => [
  {
    label: '启用',
    value: true,
  },
  {
    label: '禁用',
    value: false,
  },
])
// 查看会员详情
const handleView = async (record: MemberRecord) => {
  setLoading(true)
  try {
    const response = await getMemberDetail(record.userId)
    currentDetailMember.value = response.data

    // 构建详情数据 (保留这部分以防需要)
    detailData.value = [
      { label: '用户ID', value: currentDetailMember.value.userId },
      { label: '姓名', value: currentDetailMember.value.trueName || '未设置' },
      { label: '手机号', value: currentDetailMember.value.mobile },
      { label: '性别', value: currentDetailMember.value.sex ? '男' : '女' },
      { label: '邮箱', value: currentDetailMember.value.email || '未设置' },
      { label: '状态', value: currentDetailMember.value.status ? '启用' : '禁用' },
      { label: '固定电话', value: currentDetailMember.value.telephone || '未设置' },
      { label: '地区', value: currentDetailMember.value.area || '未设置' },
      { label: '联系地址', value: currentDetailMember.value.contactAddr || '未设置' },
      { label: 'QQ', value: currentDetailMember.value.qq || '未设置' },
      { label: '生日', value: currentDetailMember.value.birthday || '未设置' },
      { label: '注册时间', value: currentDetailMember.value.time || '未知' },
      { label: '最后登录', value: currentDetailMember.value.lastLogin || '未登录' },
    ]

    detailVisible.value = true
  } catch (error) {
    Message.error('获取会员详情失败')
    console.error('获取会员详情失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理编辑按钮点击
const handleEdit = async (record: MemberRecord) => {
  setLoading(true)
  try {
    const response = await getMemberDetail(record.userId)
    editForm.value = response.data
    editVisible.value = true
  } catch (error) {
    Message.error('获取会员信息失败')
    console.error('获取会员信息失败:', error)
  } finally {
    setLoading(false)
  }
};

// 提交编辑表单
const handleEditSubmit = async () => {
  setLoading(true)
  try {
    await updateMember(editForm.value)
    Message.success('保存成功')
    editVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('保存失败')
    console.error('保存失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理禁用/启用按钮点击
const handleToggleStatus = (record: MemberRecord) => {
  currentMember.value = record
  // 设置操作类型：true表示禁用操作，false表示启用操作
  statusAction.value = record.status
  toggleStatusVisible.value = true
};

// 确认禁用/启用
const handleToggleStatusConfirm = async () => {
  if (!currentMember.value) return

  const action = statusAction.value ? '禁用' : '启用'

  try {
    await toggleMemberStatus(currentMember.value.userId)
    Message.success(`${action}成功`)
    toggleStatusVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error(`${action}失败`)
    console.error(`${action}失败:`, error)
  }
};

// 处理删除按钮点击
const handleDelete = (record: MemberRecord) => {
  currentMember.value = record
  deleteVisible.value = true
};

// 确认删除
const handleDeleteConfirm = async () => {
  if (!currentMember.value) return

  try {
    await deleteMember([currentMember.value.userId])
    Message.success('删除成功')
    deleteVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('删除失败')
    console.error('删除失败:', error)
  }
};

const fetchData = async (params: PageQuery = { current: 1, pageSize: 20 }) => {
  setLoading(true)
  try {
    const response = await queryMemberPage(params)
    renderData.value = response.list
    pagination.current = params.current
    pagination.total = response.total
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false)
  }
}


const search = () => {
  // 构建查询参数，过滤掉空值
  const params = {
    ...basePagination,
    ...Object.entries(formModel.value).reduce((acc, [key, value]) => {
      if (value !== '' && value !== undefined && value !== null) {
        acc[key] = value;
      }
      return acc;
    }, {} as Record<string, any>)
  };

  fetchData(params as PageQuery);
}

const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current })
}

fetchData()

const reset = () => {
  formModel.value = generateFormModel()
}


const handleSelectDensity = (val: string | number | Record<string, any> | undefined, e: Event) => {
  size.value = val as SizeProps
}

const handleChange = (checked: boolean | (string | boolean | number)[], column: Column, index: number) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter((item) => item.dataIndex !== column.dataIndex)
  } else {
    cloneColumns.value.splice(index, 0, column)
  }
}


const exchangeArray = <T extends Array<any>>(array: T, beforeIdx: number, newIdx: number, isDeep = false): T => {
  const newArray = isDeep ? cloneDeep(array) : array
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop())
  }
  return newArray
}

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e
          exchangeArray(cloneColumns.value, oldIndex, newIndex)
          exchangeArray(showColumns.value, oldIndex, newIndex)
        },
      })
    })
  }
}


watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val)
      cloneColumns.value.forEach((item, index) => {
        item.checked = true
      })
      showColumns.value = cloneDeep(cloneColumns.value)
    },
    { deep: true, immediate: true }
)
</script>

<script lang="ts">
export default {
  name: 'MemberTable',
}
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}

// 删除确认对话框样式
:deep(.delete-confirm-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }

  .arco-modal-footer {
    border-top: 1px solid #f2f3f5;
    padding-top: 12px;
  }
}

.delete-confirm-content {
  display: flex;
  padding: 16px 0;

  .delete-icon {
    font-size: 48px;
    color: #f53f3f;
    margin-right: 16px;
    display: flex;
    align-items: center;
  }

  .delete-info {
    flex: 1;

    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
      color: #1d2129;
    }

    p {
      margin: 0 0 8px 0;
      color: #4e5969;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .member-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #e5e6eb;

      span {
        margin-right: 16px;
        font-weight: 500;
      }
    }
  }
}

// 状态样式
.circle {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #f53f3f;
  margin-right: 8px;

  &.pass {
    background-color: #00b42a;
  }
}

// 会员详情对话框样式
:deep(.member-detail-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }

  .arco-tabs-header {
    margin-bottom: 0;
  }
}

.member-detail-container {
  .member-detail-header {
    display: flex;
    align-items: center;
    padding-bottom: 16px;

    .avatar-container {
      position: relative;
      margin-right: 20px;

      .status-badge {
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        padding: 2px 12px;
        border-radius: 10px;
        font-size: 12px;
        background-color: #f53f3f;
        color: white;
        white-space: nowrap;
        min-width: 60px;
        text-align: center;

        &.active {
          background-color: #00b42a;
        }
      }
    }

    .basic-info {
      flex: 1;

      h2 {
        margin: 0 0 8px 0;
        font-size: 18px;
        color: #1d2129;
      }

      .info-item {
        margin-bottom: 6px;
        color: #4e5969;
        font-size: 14px;
        display: flex;
        align-items: center;

        .arco-icon {
          margin-right: 6px;
          font-size: 16px;
        }
      }
    }

    .action-buttons {
      margin-left: 20px;
    }
  }

  .detail-section {
    padding: 16px 0;

    .detail-row {
      display: flex;
      margin-bottom: 16px;

      .detail-item {
        flex: 1;
        margin-right: 16px;

        &.full-width {
          flex: 0 0 100%;
          margin-right: 0;
        }

        .detail-label {
          font-size: 13px;
          color: #86909c;
          margin-bottom: 4px;
        }

        .detail-value {
          font-size: 14px;
          color: #1d2129;
          word-break: break-word;
        }
      }
    }
  }
}

// 启用/禁用确认对话框样式
:deep(.status-confirm-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }

  .arco-modal-footer {
    border-top: 1px solid #f2f3f5;
    padding-top: 12px;
  }
}

.status-confirm-content {
  display: flex;
  padding: 16px 0;

  .status-icon {
    font-size: 48px;
    color: #00b42a;
    margin-right: 16px;
    display: flex;
    align-items: center;

    &.disable {
      color: #f53f3f;
    }
  }

  .status-info {
    flex: 1;

    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
      color: #1d2129;
    }

    p {
      margin: 0 0 8px 0;
      color: #4e5969;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .member-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #e5e6eb;

      span {
        margin-right: 16px;
        font-weight: 500;
      }
    }
  }
}
</style>
